﻿using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using PerfAssist.MemoryProfilerAdvanced.Editor;
using UnityEngine;
using UnityEditor;
using UnityEditor.MemoryProfiler;
using Treemap;

namespace MemoryProfilerWindow
{
    public class TypeManager
    {
        private static Assembly[] assemblies;
        private static Dictionary<string, Type> typedict;

        public static void Setup()
        {
            if (assemblies != null || typedict != null)
                return;

            assemblies = new Assembly[2];
            assemblies[0] = Assembly.GetAssembly(typeof(UnityEngine.Object));
            assemblies[1] = Assembly.GetAssembly(typeof(AssetDatabase));

            typedict = new Dictionary<string, Type>();
            typedict.Clear();
            for (int i = 0; i < assemblies.Length; i++)
            {
                if (assemblies[i] != null)
                {
                    Type[] ts = assemblies[i].GetTypes();
                    if (ts != null)
                    {
                        foreach (Type t in ts)
                        {
                            typedict[t.Name] = t;
                        }
                    }
                }
            }
        }

        public static Type FindType(string typename)
        {
            if (typedict == null)
                return null;

            if (typedict.ContainsKey(typename))
            {
                return typedict[typename];
            }
            else
            {
                return null;
            }
        }

        public static UnityEngine.Object GetObject(ThingInMemory thing, bool iseditor)
        {
            var nativeObject = thing as NativeUnityEngineObject;
            if (nativeObject == null)
                return null;
            
            if (iseditor)
            {
                Selection.activeInstanceID = nativeObject.instanceID;
                return Selection.activeObject;
            }
            //else
            //{
            //    if (!string.IsNullOrEmpty(nativeObject.name))
            //    {
            //        Type t = FindType(nativeObject.className);
            //        if (t != null)
            //        {
            //            UnityEngine.Object[] loadedobjs = Resources.FindObjectsOfTypeAll(t);
            //            if (loadedobjs != null)
            //            {
            //                for (int i = 0; i < loadedobjs.Length; i++)
            //                {
            //                    if (loadedobjs[i].name == nativeObject.name)
            //                    {
            //                        return loadedobjs[i];
            //                    }
            //                }
            //            }
            //        }
            //    }            
            //}
            return null;
        }
    }
}